package com.lph.health.controller;


import cn.afterturn.easypoi.excel.ExcelXorHtmlUtil;
import cn.afterturn.easypoi.excel.entity.ExcelToHtmlParams;
import com.lph.health.service.ReportService;
import com.lph.health.service.TMemberService;
import com.lph.health.service.TSetmealService;
import com.lph.health.utils.Result;
import io.swagger.annotations.Api;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  图形报表控制器
 * </p>
 *
 * @author 墨浅清谈
 * @since 2021-11-13
 */
@RestController
@Api(tags = "图形报表处理")
@RequestMapping("/report")
@Slf4j
public class ReportController {

    @Autowired
    private TMemberService memberService;

    @Autowired
    private TSetmealService setmealService;

    @Autowired
    private ReportService reportService;

    // 会员数量折线图数据  months:["2021.11.01"]\memberCount:[3]
    @GetMapping("/getMemberReport")
    public Result getMemberReport() throws Exception {
        Map<String,Object> map = new HashMap<>();
        try {
            List<String> months = new ArrayList<>();
            Calendar calendar = Calendar.getInstance();// 获取日历对象,默认为当前系统时间
            // 计算过去一年的12个月,从当月开始
            calendar.add(Calendar.MONTH, -12);// 按月份，往前推12个月
            for (int i = 0; i < 12; i++) {
                calendar.add(Calendar.MONTH, 1);// 获得当前时间(去年)往后推一个月
                Date date = calendar.getTime();// 获得日期
                // 装入List
                months.add(new SimpleDateFormat("yyyy.MM").format(date));// 转换格式为yyyy.MM
            }
            map.put("months",months);

            // 根据月份查询对应会员数量
            List<Integer> memberCount = memberService.findMemberCountByMonths(months);
            map.put("memberCount", memberCount);

            return Result.success("获取会员信息成功!", map);
        } catch (Exception e){
            return Result.failure("获取会员统计数据失败!" + e.getMessage());
        }
    }

    // 套餐预约占比饼形图 setmealNames:["套餐1"]、setmealCounts:[{value:10, name:"套餐1"}]
    @GetMapping(value = "/getSetmealReport")
    public Result getSetmealReport(){
        Map<String, Object> data = new HashMap<>();

        try{
            // 获取套餐数据(套餐名称，预约个数)
            List<Map<String, Object>> setmealCounts = setmealService.findSetmealCount();

            data.put("setmealCounts", setmealCounts);
            // 获取套餐名称
            List<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> map : setmealCounts) {
                String name = (String) map.get("name");
                setmealNames.add(name);
            }
            data.put("setmealNames", setmealNames);
            return Result.success("获取套餐占比数据成功！",data);
        } catch (Exception e){
            return Result.failure("获取套餐占比数据失败!" + e.getMessage());
        }
    }

    // 运营数据统计
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            Map<String, Object> date = reportService.getBusinessReportData();
            return Result.success("获取运营数据成功!", date);
        } catch (Exception e ){
            return Result.failure("获取运营数据失败!" + e.getMessage());
        }
    }

    // 导出运营数据
    @GetMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request,  HttpServletResponse response){
        try {
            Map<String, Object> result = reportService.getBusinessReportData();

            log.info(" ==== 进行打印 ==== ");

            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            // 获得Excel模板文件绝对路径    File.separator 相当于斜线，动态适应操作系统生成斜线
            String fileRealPath = request.getSession().getServletContext().getRealPath("templates") +
                    File.separator + "report_template.xlsx";
            log.info("获得文件路径"+fileRealPath);


            // 基于提供的Excel文件在内存中创建一个Excel 对象  构造输入流
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(fileRealPath));
            // 读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);
            // 将数据加载到对应单元格,  先获取行 再到格
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for(Map map : hotSetmeal){//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNum ++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //通过输出流进行文件下载  基于浏览器作为客户端 进行下载
            ServletOutputStream out = response.getOutputStream(); // 创建输出流
            // 设置响应信息
            response.setContentType("application/vnd.ms-excel"); // 代表excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx"); // 指定以附件的形式下载、已及下载名称
            excel.write(out);

            //准备excel转换成html
            ExcelToHtmlParams htmlParams = new ExcelToHtmlParams(excel);
            byte[] bytes = ExcelXorHtmlUtil.excelToHtml(htmlParams).getBytes();
            //将html二进制码输出给浏览器
            response.getOutputStream().write(bytes);


            out.flush();
            out.close();
            excel.close();
            log.info(" ==== 进行打印 ==== ");
            return Result.success("打印运营数据成功！");
        } catch (Exception e ){
            return Result.failure("打印运营数据失败!" + e.getMessage());
        }
    }
}

